package com.frame.auth.resource.security.exception;


import com.frame.common.core.util.ResponseUtils;
import com.frame.common.tools.result.ResultCode;
import com.frame.common.tools.result.ServiceResult;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @auther zhangwj
 * @date 2021/3/18 下午5:11
 */
public class AuthExceptionEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest httpServletRequest,
                         HttpServletResponse httpServletResponse,
                         AuthenticationException authException) throws IOException, ServletException {
        Throwable cause = authException.getCause();
        if(cause instanceof InvalidTokenException){
            ResponseUtils.writeJson(httpServletResponse, ServiceResult.getFailureResult(ResultCode.INVALID_TOKEN));
        }else {
            ResponseUtils.writeJson(httpServletResponse, ServiceResult.getFailureResult(ResultCode.ERROR));
        }
    }
}
